<?php
use think\Db;
use think\Log;
use think\Config;
use think\Exception;

//公共功能库	


     //订单对比
    function ordersidbeff($data,$value)
    {   
        if($value[0]['ordersid'] != $data['ordersid'] || $value[0]['uid'] != $data['uid'] || $value[0]['goodsprice'] != $data['goodsprice'] || !empty($value[0]['pay_order_id']))
        {   
            Log::error($value,"error orders id beff failure or order carry out");
            return true;
        }
        return false;
    }

		    /** 
     * 生成某个范围内的随机时间 
     * @param <type> $begintime  起始时间 格式为 Y-m-d H:i:s 
     * @param <type> $endtime    结束时间 格式为 Y-m-d H:i:s   
     * @param <type> $now         是否是时间戳 格式为 Boolean   
     */ 
	function randomDate($begintime, $endtime="", $now = true) {
        $begin = strtotime($begintime);  
        $end = $endtime == "" ? mktime() : strtotime($endtime);
        $timestamp = rand($begin, $end);
        // d($timestamp);
        return $now ? date("Y-m-d H:i:s", $timestamp) : $timestamp;          
    }
	
    //爱上充值asSign验证规则
    //验证规则
    function asHmacMd5($data,$key)           
    {                                      
        # RFC 2104 HMAC implementation for php.
        # Creates an md5 HMAC.                 
        # Eliminates the need to install mhash to compute a HMAC
        # Hacked by Lance Rushing(NOTE: Hacked means written)
                                               
        #需要配置环境支持iconv，否则中文参数不能正常处理
        $key = iconv("GBK","UTF-8",$key);  
        $data = iconv("GBK","UTF-8",$data);
                                               
        $b = 64; # byte length for md5         
        if (strlen($key) > $b) {               
        $key = pack("H*",md5($key));           
        }                                      
        $key = str_pad($key, $b, chr(0x00));   
        $ipad = str_pad('', $b, chr(0x36));    
        $opad = str_pad('', $b, chr(0x5c));    
        $k_ipad = $key ^ $ipad ;               
        $k_opad = $key ^ $opad;                
                                               
        return md5($k_opad . pack("H*",md5($k_ipad . $data)));
    }

     //返回错误消息
     function resError($msg)
    {
        $req=[];
        $req['code'] = 1;
        $req['msg'] = $msg;
        return json_encode($req);
    }

    //成功返回结构
    function resoK()
    {
        $req=[];
        $req['code'] = 0;
        $req['msg'] = 'ok';
        return json_encode($req);
    }
    
    //获取时间戳毫秒级
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
    
    /**
     * 生成订单号
     * @param int $payment
     */
    function getOrderID($payment=0){
        if($payment == 0){
            //支付宝
            $orderID = 'zf'.date('YmdHi',time()).rand(1000,9999);
        }elseif($payment == 1){
            //微信支付
            $orderID = 'wx'.date('YmdHi',time()).rand(1000,9999);
        }elseif($payment == 3){
            //苹果
            $orderID = 'ap'.date('YmdHi',time()).rand(1000,9999);
        }else{
            return false;
        }
        if(Db::table('fa_y_onlineorder')->where(['orderID'=>$orderID])->find()){
            $orderID = getOrderID($payment);
        }
        return $orderID;
    }
    
    /**
     * IOS 服务器二次验证代码
     * @author violet
     * @since 2017-11-27
     */
    function getReceiptData($receipt, $isSandbox = false)
    {
        if ($isSandbox) {
            $endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';
        }
        else {
            $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';
        }
    
        $postData = json_encode(
            array('receipt-data' => $receipt)
        );
    
        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);  //这两行一定要加，不加会报SSL 错误
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
    
        $response = curl_exec($ch);
        $errno    = curl_errno($ch);
        $errmsg   = curl_error($ch);
        curl_close($ch);
        //判断时候出错，抛出异常
        if ($errno != 0) {
            throw new Exception($errmsg, $errno);
        }
    
        $data = json_decode($response);
        //判断返回的数据是否是对象
        if (!is_object($data)) {
            throw new Exception('Invalid response data');
        }
        //判断购买时候成功
        if (!isset($data->status) || $data->status != 0) {
            throw new Exception('Invalid receipt');
        }
    
        //返回信息
        return true;
    }